<!--
 * @description  : 地图-查看零售户信息
 * @descriptionDetail: 地图-查看零售户信息
 * @copyright    : 浙江烟草
 * @author       : zhaowb
 * @create       : 2024-05-18 18:43:02
-->
<template>
	<view class="page">
		<!-- #ifdef H5-ONLY -->
		<theme-navbar :is-white="false" :title="navTitle"
                  :custom-back="retailBack" style="z-index: 99999"></theme-navbar>
		<!-- #endif -->

		<view class="m-content">
			<!-- 地图展示 -->
			<view :style="{	height: getContainerHeight()}" id="container"></view>
      <!-- 零售户列表 -->
      <view style="margin: 10rpx;">
        <view class="drag-item" v-for="(sc, idx) in archiveList" :key="idx">
          {{ sc.companyName }}{{ getDistanceXp(sc) }}
        </view>
      </view>
    </view>
	</view>
</template>

<script>
	import {
		AMapMixin,
	} from '@/common/AMapMixin.js';
	import certificateService from '@/service/certificate/certificate.service.js';
	import {
		SET_MAP_LAT_LON,
	} from '@/config/setting.config.js';
	import USearch from '../../../uview-ui/components/u-search/u-search.vue';
	import UIcon from '../../../uview-ui/components/u-icon/u-icon.vue';
  import draggable from 'vuedraggable';

	export default {
		components: {
      draggable,
			UIcon,
			USearch,
		},
		mixins: [AMapMixin, ],
		data() {
			return {
				markers: [],// 加入地图的标记点数据
				currPosition: undefined,
				archiveList: [], // 地图范围内查询出来的零售户数据
				allArchiveList: [], // 所有已经渲染到地图上的零售户数据
        tmpArchiveList: [],
        newArchiveList: [],
				northeastLatitude: '',
				northeastLongitude: '',
				southwestLatitude: '',
				southwestLongitude: '',
				cluster: undefined,
				title: '',
				longitude: '',
				latitude: '',
				orgUuid: '',
				positionPicker: undefined,
			};
		},
		onLoad(opt) {
			this.showDefaultTitle = false;
			this.judgmentInit(opt);
			let self = this;
			if (this.$deviceApi.geolocation) {
				this.$deviceApi.geolocation().then((res) => {
					self.longitude = res.longitude;
					self.latitude = res.latitude;
				});
			} else {
				self.longitude = SET_MAP_LAT_LON[0];
				self.latitude = SET_MAP_LAT_LON[1];
			}
		},
		mounted() {
			this.init();
		},
		methods: {
			init() {
				this.$modal.showLoading('地图加载中...');
			},
      getDistanceXp(tmp) {
        if (tmp.distance) {
          return '[' + tmp.distance + '米]';
        }
        return '';
      },
			judgmentInit(opt) {
				this.title = '查看周边零售户';
				this.updateMixinTitle(this.title);
			},
			initAmap() {
				let self = this;
				// #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
				this.$deviceApi.geolocation().then(
					(res) => {
						self.curPos = [res.longitude, res.latitude];
						self.setMapInstance([res.longitude, res.latitude]);
					},
					(err) => {
						self.curPos = SET_MAP_LAT_LON;
						self.setMapInstance(SET_MAP_LAT_LON);
					}
				);
				// #endif
				// #ifdef H5-ONLY
				this.getCurrentLocation().then(
					(res) => {
						self.curPos = [res.lng, res.lat, ];
						self.setMapInstance([res.lng, res.lat, ]);
					},
					(err) => {
						self.curPos = SET_MAP_LAT_LON;
						self.setMapInstance(SET_MAP_LAT_LON);
					}
				);
				// #endif
			},
			setMapInstance(cords) {
				if (!this.hasInited) return;
				let self = this;
				self.curCords = new AMap.LngLat(cords[0], cords[1]);
				self.amap = new AMap.Map('container', {
					center: self.curCords,
					showControlButton: true,
          zoomEnable: false,
					zoom: 17,
				});
				// self.amap.setZooms([13, 30,]);
				self.setCurrentPointMarker();
				this.$modal.hideLoading();
				self.loadPlugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.MapType', ], function() {
					// 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
					// self.amap.addControl(new AMap.ToolBar());
					// 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
					self.amap.addControl(new AMap.Scale());
					// 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
					let geolocation = new AMap.Geolocation({
						enableHighAccuracy: true, // 是否使用高精度定位，默认:true
						timeout: 10000, // 超过10秒后停止定位，默认：5s
						// buttonPosition:'RB',    //定位按钮的停靠位置
						buttonOffset: new AMap.Pixel(5, 10), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
						// zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
						content: '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>',
					});
					self.amap.addControl(geolocation);
				});
				// 地图缩放
				self.amap.on('zoomend', function() {
					self.getNearRetailer();
				});
				// 地图移动
				self.amap.on('moveend', function() {
					self.getNearRetailer();
				});
				self.getNearRetailer();
			},
			// 获取列表数据
			getNearRetailer() {
				let bounds = this.amap.getBounds();
				let params;
				let self = this;
				let information = '';
				let errInfo = '';
				let fun = '';
        params = {
          longitudeStart: bounds.southwest.lng, // 西南
          latitudeStart: bounds.southwest.lat,
          longitudeEnd: bounds.northeast.lng,
          latitudeEnd: bounds.northeast.lat,
          licStatus: ['01', '02', '10', ],
        };
        information = '正在查询周边零售户...';
        errInfo = '该区域内没查询到零售户信息！';
        fun = certificateService.listRetailInScope;

				if (this.amap.getZoom() < 2) {
					// this.markers = [];
					if (this.cluster) {
						this.amap.remove(this.cluster);
					}
					if (this.$storage.get('showMapZoomTip') != '1') {
						this.$modal.alert(
							'地图层级收缩，不支持查询，查询数据请将地图层级扩大。',
							'提示',
							() => {
								this.$storage.set('showMapZoomTip', '1');
							},
							'不再提示'
						);
					}
					return;
				}
				this.$modal.showLoading(information);
				// this.markers = [];
				fun(params)
					.then((res) => {
						this.$modal.hideLoading();
						if (res.success) {
							if (res.data.length != 0) {
                // 将查询出来的数据和已经渲染的节点数据对比，渲染差集数据
                let noArchiveList  = res.data.filter(item => !self.allArchiveList.some(obj=> obj.retailerUuid === item.retailerUuid));
                noArchiveList.forEach((retailer, index) => {
									if (retailer.latitude && retailer.longitude) {
										this.addMarker(retailer, res.data);
									}
								});
                self.archiveList = res.data;
                // 计算步行
                self.calculateDistanceAndSort(3);

                self.allArchiveList.push(noArchiveList)
								// this.markerCluster();

							} else {
                self.archiveList = res.data;
								this.$u.toast(errInfo);
							}
						} else {
							this.$modal.hideLoading();
							self.$u.toast(res.msg);
						}
					})
					.catch((error) => {
						self.$u.toast(error);
					});
			},
			// 在地图上添加点
			addMarker(retailer, retailerData) {
				let self = this;
				let markPoint = {
					title: retailer.companyName, // 显示的零售户名称
					icon: new AMap.Icon({
						size: new AMap.Size(26, 26), // 图标尺寸
            image: 'static/check/marker_selected.png', // Icon的图像
						imageSize: new AMap.Size(26, 26), //,
					}),
					label: null,
					offset: new AMap.Pixel(-15, -15),
					position: [retailer.longitude, retailer.latitude, ], // 所需要的零售户经纬度
				};
        markPoint.label = {
          content: retailer.companyName,
          offset: new AMap.Pixel(24, 1),
        };

        // 判断查询出来的零售户数据是否大于30 如果大于去掉文字提示
				// if (retailerData.length < 60) {
				// 	markPoint.label = {
				// 		content: retailer.companyName,
				// 		offset: new AMap.Pixel(24, 1),
				// 	};
				// }else {
        //   for (let i = 0; i < this.markers.length; i++) {
        //     let marker = this.markers[i];
        //     marker.setLabel(null)
        //   }
        // }
				let point = new AMap.Marker(markPoint);

				point.setMap(this.amap); // 在地图上添加点
				point.on('click', function() {
					self.showRetailer(retailer); // 点击调用详情
				});
				this.markers.push(point);
			},
      calculateDistanceAndSort(type) {
        let self = this;
        if (self.curPos == undefined || self.curPos.length != 2) {
          this.$u.toast('当前位置获取失败,稍后重试');
          this.getCurrentLocation().then(
              (res) => {
                self.curPos = [res.lng, res.lat];
              },
              (err) => {}
          );
          return;
        }
        this.$modal.showLoading('正在计算' + (type == 1 ? '驾车' : '步行') + '距离并排序...');
        this.tmpArchiveList = this.$u.deepClone(this.archiveList);
        this.newArchiveList = [];
        this.getDistance(self.curPos.join(','), this.tmpArchiveList, type);
      },
      // 距离测量
      // type  1 驾车  3 步行
      getDistance(desNow, checkLists, type) {
        let self = this;
        const SERVER_KEY = process.uniEnv.AMAP.SERVER_KEY;
        let arr = [] ;
        // 一次只查询最多100条数据 查询点太多会报错
        if (checkLists.length > 100){
          for (let i = 0; i < 100; i++) {
            let tmp = checkLists[i];
            arr.push(`${tmp.longitude},${tmp.latitude}`)
          }
        }else {
          arr = checkLists.map(({
                                  latitude,
                                  longitude
                                }) => {
            return `${longitude},${latitude}`;
          });
        }
        this.getCurDistance({
          destination: desNow,
          key: SERVER_KEY, // 很重要，不能删，占位置
          origins: arr.join('|'),
          output: 'JSON',
          type: type,
        })
            .then((rs) => {
              // 顺序循环取出查询的距离数据 赋值到零售户列表当中
              for (let i = 0; i <  checkLists.length; i++) {
                let tmp = checkLists[i];
                let disData = rs[i];
                if (disData){
                  self.$set(tmp, 'distance', disData.distance);
                  self.newArchiveList.push(tmp);
                }
              }
              // 将查询数据和已处理数据对比 取出其中未处理的数据 递归处理
              let noArchiveList  = checkLists.filter(item => !self.newArchiveList.some(obj=> obj.retailerUuid === item.retailerUuid));
              if (noArchiveList.length >  0) {
                self.getDistance(desNow, noArchiveList, type);
              } else {
                self.$modal.hideLoading();
                // 根据距离排序
                self.newArchiveList.sort((a, b) => {
                  return a.distance - b.distance;
                });
                self.archiveList = [];
                self.archiveList = [...self.newArchiveList];
              }
            })
            .catch((e) => {
              self.$modal.hideLoading();
              self.$u.toast('排序失败');
            });
      },
			// 点聚合方法 将一定范围内的零售户聚合起来 展示数量 暂时不用了
			markerCluster() {
				let self = this;
				let count = this.markers.length;
				let renderClusterMarkers = function(context) {
					let factor = Math.pow(context.count / count, 1 / 18);
					let div = document.createElement('div');
					let Hue = 180 - factor * 180;
					let bgColor = 'hsla(' + Hue + ',100%,50%,0.7)';
					let fontColor = 'hsla(' + Hue + ',100%,20%,1)';
					let borderColor = 'hsla(' + Hue + ',100%,40%,1)';
					let shadowColor = 'hsla(' + Hue + ',100%,50%,1)';
					div.style.backgroundColor = bgColor;
					let size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
					div.style.width = div.style.height = size + 'px';
					div.style.border = 'solid 1px ' + borderColor;
					div.style.borderRadius = size / 2 + 'px';
					div.style.boxShadow = '0 0 1px ' + shadowColor;
					div.innerHTML = context.count;
					div.style.lineHeight = size + 'px';
					div.style.color = fontColor;
					div.style.fontSize = '14px';
					div.style.textAlign = 'center';
					context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
					context.marker.setContent(div);
				};
				this.amap.plugin(['AMap.MarkerClusterer', ], function() {
					if (self.cluster) {
						self.cluster.setMap(null);
					}
					self.cluster = new AMap.MarkerClusterer(
						self.amap, // 地图实例
						self.markers, // 海量点组成的数组
						{
							gridSize: 80,
							renderClusterMarker: renderClusterMarkers,
						}
					);
				});
			},
			// 查看零售户详情
			showRetailer(retailer) {
        this.$u.route('pages/retailer/retailerInfo/retailerInfo', {
          retailerUuid: retailer.retailerUuid,
        });
			},
			toCurrent() {
				let self = this;
				this.getCurrentLocation().then(
					(res) => {
						self.curCords = new AMap.LngLat(res.lng, res.lat);
						self.curPos = [res.lng, res.lat, ];
						self.updateCurrentPointMarker();
					},
					(err) => {
						self.updateCurrentPointMarker();
					}
				);
			},
			getContainerHeight() {
        let p = (this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight) / 1.8  + 'px';
        // #ifdef H5-DINGDING
        p = (this.$u.sys().windowHeight - this.$u.sys().statusBarHeight) / 1.8 + 'px';
        // #endif
        return p;
			},
			getContainerWidth() {
				return this.$u.sys().windowWidth + 'px';
			},
			justInitMap() {
				this.$modal.alert('请在设备的设置中开启APP的定位权限后重新获取当前位置');
				this.amap = new AMap.Map('container', {
					showControlButton: true,
					zoom: 18,
				});
				this.$modal.hideLoading();
			},
			// 返回按钮
			retailBack() {
				this.$deviceApi.nfcStop && this.$deviceApi.nfcStop();
				let self = this;
				self.backPrev({
					paramKey: 'data',
					param: {},
				});
			},
		},
	};
</script>

<style scoped lang="scss">
	.page {
		padding: 0;
	}

	@import 'style/certificate/common.scss';

	.nolicence-search-lay {
		position: fixed;
		// #ifndef H5-DINGDING
		top: 44px;
		// #endif
		// #ifdef H5-DINGDING
		top: 0px;
		// #endif
		z-index: 99;
		width: 100%;
		padding: $cm-search-padding-row 0;
	}

	.search-right-icon {
		display: flex;
		position: absolute;
		right: 8%;
	}

	uni-page-body {
		min-height: 100%;
		width: 100%;
	}

	#container {
    width: 100%;
    height: 60%;
	}
  .drag-item {
    padding: 8px 10px;
    border-bottom: 1px solid #eee;
  }

	.u-search-title {
		background: #fff;
		padding: 10px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 44px;
	}

	.u-search-btn {
		height: 44px;
		line-height: 44px;
		// padding: 0 10px;
		display: flex;
		align-items: center;
		margin: 0 20rpx;

		.u-confirm-btn {
			height: 32px;
			margin-left: 10px;
		}
	}

	// 搜索框内容
	.u-serach-info {
		background-color: #f4f4f5;
		position: fixed;
		/* #ifdef H5-DINGDING  */
		top: 0px;
		/* #endif */
		/* #ifndef H5-DINGDING  */
		top: calc(var(--status-bar-height) + 44px);
		/* #endif */
		z-index: 1;
		width: 100%;
		padding-right: 11px;
	}

	.u-l-item {
		margin-top: 88px;
	}

	.cur-loc {
		position: absolute;
		bottom: 30px;
		left: 10px;
		padding: 5px;
		background: #fff;
		width: 35px;
		height: 35px;
		box-shadow: 0px 0px 0px 1px #ddd;
	}
</style>
